import axios from 'axios'
import { ElMessage } from 'element-plus'
import { refreshToken } from '../api/user'
import { showElMessage } from './tools'

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    // headers: {
    //     'Content-Type': 'application/json',
    // },
    timeout: 5000 // request timeout
})

// request interceptor 请求拦截器
service.interceptors.request.use(
    async config => {
        const token = localStorage.getItem("access_token")
        if (token) {
            config.headers["Authorization"] = 'Bearer ' + token
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// 标记是否正在刷新token
let isRefreshing = false
// 需要重复请求的操作数组
let retryRequests = []

// response interceptor 响应拦截器
service.interceptors.response.use(
    async (response) => {
        const res = response.data

        if (res.code !== 200) {
            // token 失效处理
            if (res.code === 1024) {
                if (!isRefreshing) {
                    // 没刷新，尝试先刷新
                    isRefreshing = true
                    try {
                        const aToken = localStorage.getItem("access_token")
                        const rToken = localStorage.getItem("refresh_token")
                        const res = await refreshToken({
                            "access_token": aToken,
                            "refresh_token": rToken
                        });
                        localStorage.setItem("access_token", res.data.access_token)
                        localStorage.setItem("refresh_token", res.data.refresh_token)
                        // 刷新成功，携带新token重新执行失败的请求
                        retryRequests.forEach((item: any) => item(res.data?.access_token))
                        retryRequests = []
                        // 当前这个请求也需要重复请求一次，因为加入数组晚于执行数组
                        return service(response.config)
                    } catch (error) {
                        // 刷新令牌失败，跳转至登录页
                        localStorage.clear()
                        window.location.href = "/login"
                        return Promise.reject(error)
                    }
                }
                return new Promise((resolve, reject) => {
                    // @ts-ignore
                    retryRequests.push((aToken) => {
                        // 重复请求数组数据需要根据新token修改请求头
                        response.config.headers.Authorization = `Bearer ${aToken}`
                        // 重新发起请求后，将后端返回的数据resolve
                        service(response.config)
                            .then((res) => {
                                resolve(res)
                            })
                            .catch((error) => {
                                reject(error)
                            })
                    })
                })
            }
            // 显示错误消息
            showElMessage(res, 'error')
            return
        } else {
            return res
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export default service